package com.aiti.lulian.service.newCard;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.page.PageInfo;
import com.aiti.base.core.page.PageResult;
import com.aiti.lulian.dto.newCard.ExchangeCardParamDto;
import com.aiti.lulian.dto.newCard.MyCardHolderParamDto;
import com.aiti.lulian.dto.newCard.MyExchangeRequestPageParamDto;
import com.aiti.lulian.entity.CardHolder;
import com.aiti.lulian.entity.newCard.CardUserExtraUnion;
import com.aiti.lulian.mapper.newCard.CardExchangeMapper;
import com.aiti.lulian.service.CardHolderService;
import com.aiti.lulian.service.ICardVisitorRecordService;
import com.aiti.lulian.vo.newCard.ExchangeCardListVo;
import com.aiti.lulian.vo.newCard.MyCardHolderVo;
import com.aiti.lulian.vo.newCard.MyExchangeRequestVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * description: 交换名片
 * auth fcb
 * date 2025-08-13 13:58
 **/
@Service
@Slf4j
public class CardExchangeService {

    @Autowired
    private CardExchangeMapper cardExchangeMapper;
    @Autowired
    private ICardVisitorRecordService cardVisitorRecordService;
    @Autowired
    private CardHolderService cardHolderService;

    /**
     * 交换名片时查询我的名片列表
     * @param userId
     * @return
     */
    public List<ExchangeCardListVo> queryExchangeCardList(String userId) {
        List<ExchangeCardListVo> list = cardExchangeMapper.queryExchangeCardList(userId);
        return list;
    }

    /**
     * 发送交换名片请求
     * @param paramDto
     */
    @Transactional(rollbackFor = Exception.class)
    public void exchangeCard(ExchangeCardParamDto paramDto) {
        this.checkExchangeParam(paramDto);
        // 1. 查询名片是否已经交换过，（不包含被忽略的）
        Integer existChangeCount = cardExchangeMapper.queryExchangeCount(paramDto);
        if(existChangeCount > 0) {
            throw new BusinessException("已与对方交换过该名片");
        }
        // 判断当前被交换的名片是不是自己的其他名片
        Integer myCardCount = cardExchangeMapper.queryMyCardCount(paramDto.getFromUserId(), paramDto.getToCardId());
        if(myCardCount > 0) {
            throw new BusinessException("无法与自己创建的名片进行交换");
        }
        // 2. 保存交换请求
        this.saveExchangeRequest(paramDto);
        // todo 3. 通过微信发送信息

        // 4. 更新访客记录中名片交换状态：已发送交换请求
        cardExchangeMapper.updateVisitorRecordExchangeStatus(paramDto.getFromUserId(), paramDto.getToUserId(), paramDto.getFromCardId(),"1", paramDto.getToCardId());
    }

    /**
     * 查询别人向我发起的交换请求通知列表
     * @param userId
     */
    public List<MyExchangeRequestVo> queryMyExchangeRequestList(String userId) {
        List<MyExchangeRequestVo> list = cardExchangeMapper.queryMyExchangeRequestList(userId);
        return list;
    }

    /**
     * 更新交换状态
     * @param baseId card_user_extra_union表主键
     * @param enable 0:等待对方审核 2:忽略 1:同意
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateExchangeStatus(String baseId, String enable) {
        if("2".equals( enable)) {
            cardExchangeMapper.updateEnableByBaseId(baseId, enable);
        }else if("1".equals( enable)) {
            // 1.更新状态
            cardExchangeMapper.updateEnableByBaseId(baseId, enable);
            // 2. 保存到名片夹。给交换双方各增加一条数据
            CardUserExtraUnion cardUserExtraUnion = cardExchangeMapper.queryCardUserExtraUnionByBaseId(baseId);
            List<CardHolder> list = new ArrayList<>();
            LambdaQueryWrapper<CardHolder> queryWrapper_1 = new LambdaQueryWrapper<CardHolder>()
                    .eq(CardHolder::getBaseUserId, cardUserExtraUnion.getFromUserId())
                    .eq(CardHolder::getCardHolderUserId, cardUserExtraUnion.getToUserId())
                    .eq(CardHolder::getUserCardId, cardUserExtraUnion.getFromCardId())
                    .eq(CardHolder::getUserHolderCardId, cardUserExtraUnion.getToCardId());
            List<CardHolder> list1 = cardHolderService.list(queryWrapper_1);
            if (list1.isEmpty()) {
                CardHolder cardHolder1 = new CardHolder();
                cardHolder1.setBaseId(IdUtil.simpleUUID());
                cardHolder1.setBaseCreateTime(DateUtil.date());
                cardHolder1.setCardHolderUserId(cardUserExtraUnion.getToUserId());
                cardHolder1.setBaseUserId(cardUserExtraUnion.getFromUserId());
                cardHolder1.setUserCardId(cardUserExtraUnion.getFromCardId());
                cardHolder1.setUserHolderCardId(cardUserExtraUnion.getToCardId());
                list.add(cardHolder1);
            }
            LambdaQueryWrapper<CardHolder> queryWrapper_2 = new LambdaQueryWrapper<CardHolder>()
                    .eq(CardHolder::getBaseUserId, cardUserExtraUnion.getToUserId())
                    .eq(CardHolder::getCardHolderUserId, cardUserExtraUnion.getFromUserId())
                    .eq(CardHolder::getUserCardId, cardUserExtraUnion.getToCardId())
                    .eq(CardHolder::getUserHolderCardId, cardUserExtraUnion.getFromCardId());
            List<CardHolder> list2 = cardHolderService.list(queryWrapper_2);
            if (list2.isEmpty()) {
                CardHolder cardHolder2 = new CardHolder();
                cardHolder2.setBaseId(IdUtil.simpleUUID());
                cardHolder2.setBaseCreateTime(DateUtil.date());
                cardHolder2.setCardHolderUserId(cardUserExtraUnion.getFromUserId());
                cardHolder2.setBaseUserId(cardUserExtraUnion.getToUserId());
                cardHolder2.setUserCardId(cardUserExtraUnion.getToCardId());
                cardHolder2.setUserHolderCardId(cardUserExtraUnion.getFromCardId());
                list.add(cardHolder2);
            }
            if(!list.isEmpty()) {
                cardHolderService.saveBatch(list);
            }
            // 3. 更新访客状态
            cardExchangeMapper.updateVisitorRecordExchangeStatus(cardUserExtraUnion.getFromUserId(), cardUserExtraUnion.getToUserId(), cardUserExtraUnion.getFromCardId(),"2", cardUserExtraUnion.getToCardId());

        }
    }

    /**
     * 查询我的交换请求列表
     * @param paramDto
     */
    public PageResult<MyExchangeRequestVo> queryMyExchangeRequestPageList(MyExchangeRequestPageParamDto paramDto) {
        IPage<MyExchangeRequestVo> page = new Page<>(paramDto.getPageNum(), paramDto.getPageSize());
        List<MyExchangeRequestVo> list = cardExchangeMapper.queryMyExchangeRequestPageList(page, paramDto);
        PageResult<MyExchangeRequestVo> pageResult = new PageResult<>(list, new PageInfo(paramDto.getPageNum(), paramDto.getPageSize()), page.getTotal());
        return pageResult;
    }

    /**
     * 查询我的待处理的交换请求的数量
     * @param userId
     */
    public Integer queryMyExchangeRequestCount(String userId) {
        return cardExchangeMapper.queryMyExchangeRequestCount(userId, "0");
    }

    /**
     * 查询我的名片夹列表
     * @param paramDto
     * @return
     */
    public PageResult<MyCardHolderVo> queryMyCardHolderList(MyCardHolderParamDto paramDto) {
        IPage<MyCardHolderVo> page = new Page<>(paramDto.getPageNum(), paramDto.getPageSize());
        List<MyCardHolderVo> list = cardExchangeMapper.queryMyCardHolderList(page, paramDto);
        PageResult<MyCardHolderVo> pageResult = new PageResult<>(list, new PageInfo(paramDto.getPageNum(), paramDto.getPageSize()), page.getTotal());
        return pageResult;
    }

    /**
     * 删除名片夹中的名片
     * @param fromUserId 当前用户id
     * @param toCardId 要删除的名片id
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserHolderCard (String fromUserId, String toCardId) {
        cardExchangeMapper.deleteUserHolderCard(fromUserId, toCardId);
    }

    private void saveExchangeRequest(ExchangeCardParamDto paramDto) {
        CardUserExtraUnion po = new CardUserExtraUnion();
        po.setBaseId(IdUtil.simpleUUID());
        po.setFromUserId(paramDto.getFromUserId());
        po.setToUserId(paramDto.getToUserId());
        po.setFromCardId(paramDto.getFromCardId());
        po.setToCardId(paramDto.getToCardId());
        po.setExchangeSource(paramDto.getExchangeSource());
        po.setBaseCreateTime(new Date());
        po.setExchangeSource(paramDto.getExchangeSource());
        // 等待对方审核
        po.setEnable("0");
        cardExchangeMapper.saveExchangeRequest(po);
    }

    private void checkExchangeParam(ExchangeCardParamDto paramDto) {
        if(StrUtil.isBlank(paramDto.getFromUserId())) {
            throw new BusinessException("参数错误");
        }
        if(StrUtil.isBlank(paramDto.getToUserId())) {
            throw new BusinessException("参数错误");
        }
        if(StrUtil.isBlank(paramDto.getFromCardId())) {
            throw new BusinessException("参数错误");
        }
        if(StrUtil.isBlank(paramDto.getToCardId())) {
            throw new BusinessException("参数错误");
        }
    }

}
